﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace huqiang.Collections
{
    public class FastList<T> where T : struct, IClear, IDisposable
    {
        T[] buf;
        int len;
        int max = 0;
        public ref T this[int index]
        {
            get
            {
                return ref buf[index];
            }
        }

        public int Count { get => max; }
        public int Remain { get => len - max; }
        public FastList(int length=256) 
        {
            buf = new T[length];
            max = 0;
            len = length;
        }
        public void Add(ref T t)
        {
            if (max < len)
            {
                buf[max] = t;
                max++;
            }   
        }
        public void RemoveAt(int index)
        {
            if(index<=max)
            {
                if(max>0)
                {
                    max--;
                    buf[index] = buf[max];
                    buf[max].Clear();
                }
            }
        }
        public void DispsoseAt(int index)
        {
            if (index <= max)
            {
                if (max > 0)
                {
                    max--;
                    buf[index].Dispose();
                    buf[index] = buf[max];
                    buf[max].Clear();
                }
            }
        }
        public void Clear()
        {
            for (int i = 0; i < max; i++)
                buf[i].Clear();
            max = 0;
        }
    }
}
